package intranet.client;
/**
 * @author Baptiste RENDU
 */
import java.util.ArrayList;
import java.util.HashMap;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class AdminUser extends HorizontalPanel
{
	
	protected ListBox teacherList,rightsBox,coursesBox;
	protected HorizontalPanel subjectPanel,addRemovePanel;
	protected ListBox subjectList1, subjectList2;
	protected VerticalPanel buttonSubjectPanel,teacherPanel,modifPanel,quotaPanel;
	protected Grid modifGrid;
	protected PushButton addTeacherButton, removeTeacherButton,addSubjectButton, removeSubjectButton,validSubjectButton;
	protected ArrayList<String> listTeachedSubject;
	protected ValidIntegerTextBox quotaTextBox;
	protected DialogBox addBox;
	
	private final DataBaseServiceAsync dataService = GWT
	.create(DataBaseService.class);
	
	private final AddUserServiceAsync addUserService = GWT
	.create(AddUserService.class);
	/**
	 * créé un panel contenant le module AdminUser
	 * @param la session de l'utilisateur courant
	 */
	public AdminUser (Session s)
	{
		rightsBox = new ListBox();
		coursesBox = new ListBox();
		coursesBox.setEnabled(false);
		modifGrid=new Grid(3,2);

		teacherPanel=new VerticalPanel();
		teacherPanel.setHorizontalAlignment(ALIGN_CENTER);
		
		teacherList = new ListBox();
		teacherList.setVisibleItemCount(10);
		
		addTeacherButton = new PushButton(new Image("add.png"));
		addTeacherButton.setSize("20px","20px");
		addTeacherButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				addBox = new DialogBox();
				addBox.setAnimationEnabled(true);
				addBox.setGlassEnabled(true);
				addBox.setPopupPosition(300, 300);
				add(addBox);
				addBox.setTitle("Ajout Utilisateur");
				Grid addBoxPanel = new Grid(7,2);
				final TextBox firstname = new TextBox();
				final TextBox name = new TextBox();
				final TextBox log = new TextBox();
				final ListBox status = new ListBox();
				final ListBox courses = new ListBox();
				courses.setEnabled(false);
				final ValidIntegerTextBox quota = new ValidIntegerTextBox();
				quota.setText("0.0");
				final PushButton ok = new PushButton("Valider");
				
				status.addItem("Administrateur","0");
				status.addItem("Chef de filière","-1");
				status.addItem("Professeur","-1");
				
				status.addChangeHandler(new ChangeHandler() {
					
					@Override
					public void onChange(ChangeEvent event) {
						// TODO Auto-generated method stub
						if(((ListBox)event.getSource()).getSelectedIndex()!=1)
						{
							courses.setEnabled(false);
						}
						else
						{
							courses.setEnabled(true);
						}
							
					}
				});
				dataService.select("select course_id, course_name from course", new AsyncCallback<HashMap<String,String[]>>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onSuccess(HashMap<String, String[]> result) {
						// TODO Auto-generated method stub
						for(int i=0;i<result.get("course_id").length;i++)
						{
							courses.addItem(result.get("course_name")[i],result.get("course_id")[i]);
						}
					}
				});
				
				
				
				ok.setEnabled(false);
				firstname.addKeyUpHandler(new KeyUpHandler(){
					
					@Override
					public void onKeyUp(KeyUpEvent event) {
						// TODO Auto-generated method stub
						if(!firstname.getText().equals("") && !name.getText().equals(""))
						{
							ok.setEnabled(true);
						}
						else
						{
							ok.setEnabled(false);
						}
						log.setText((firstname.getText().charAt(0)+name.getText()).toLowerCase());					
					}
				});
				
				name.addKeyUpHandler(new KeyUpHandler(){
					@Override
					public void onKeyUp(KeyUpEvent event) {
						// TODO Auto-generated method stub
						if(!firstname.getText().equals("") && !name.getText().equals(""))
						{
							ok.setEnabled(true);
						}
						else
						{
							ok.setEnabled(false);
						}
						log.setText((firstname.getText().charAt(0)+name.getText()).toLowerCase());
					
					}
				});
				
				log.setEnabled(false);
				
				
				ok.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						// TODO Auto-generated method stub
						int stat=-1;
						if(status.getSelectedIndex()==1)
							stat=new Integer(courses.getValue(courses.getSelectedIndex()));
						else
							stat=new Integer(status.getValue(status.getSelectedIndex()));
						
						addUserService.addUser(log.getText(), name.getText(), firstname.getText(), stat, new Double(quota.getText()) , new AsyncCallback<Boolean>() {

							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub
								Window.alert("Erreur lors de l'ajout");
							}

							@Override
							public void onSuccess(Boolean result) {
								// TODO Auto-generated method stub
								if (!result)
									Window.alert("Erreur lors de l'ajout");
							}
						});
						addBox.hide(true);
					}
				});
				PushButton cancel = new PushButton("Annuler");
				cancel.addClickHandler(new ClickHandler() {
					
					@Override
					public void onClick(ClickEvent event) {
						// TODO Auto-generated method stub
						addBox.hide(true);
					}
				});
				
				addBoxPanel.setWidget(0,0, new Label("Prénom"));
				addBoxPanel.setWidget(0,1, firstname);
				
				addBoxPanel.setWidget(1,0, new Label("Nom"));
				addBoxPanel.setWidget(1,1, name);

				addBoxPanel.setWidget(2,0, new Label("Login"));
				addBoxPanel.setWidget(2,1, log);
			
				addBoxPanel.setWidget(3,0, new Label("Statut"));
				addBoxPanel.setWidget(3,1, status);
				
				addBoxPanel.setWidget(4,0, new Label("Filière"));
				addBoxPanel.setWidget(4,1, courses);
				
				addBoxPanel.setWidget(5,0, new Label("Quota"));
				addBoxPanel.setWidget(5,1, quota);
				
				addBoxPanel.setWidget(6,0, ok);
				addBoxPanel.setWidget(6,1, cancel);

				addBox.add(addBoxPanel);
				
				addBox.show();
			}
		});
		removeTeacherButton = new PushButton(new Image("delete.png"));
		removeTeacherButton.setSize("20px","20px");
		removeTeacherButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				if(Window.confirm("Êtes-vous sûr de vouloir supprimer cet utilisateur? Toutes les données le concernant seront perdues"))
				{
					dataService.delete("delete from teacher_event where teacher_login='"+teacherList.getValue(teacherList.getSelectedIndex())+"'", new AsyncCallback<Integer>() {

						@Override
						public void onFailure(Throwable caught) {
							// TODO Auto-generated method stub
							Window.alert("Problème de base de données. Veuillez recharger la page.");
						}

						@Override
						public void onSuccess(Integer result) {
							// TODO Auto-generated method stub , teacher_template, teacher_document, teacher_subject 
							
							dataService.delete("delete from teacher_template where teacher_login='"+teacherList.getValue(teacherList.getSelectedIndex())+"'", new AsyncCallback<Integer>() {

								@Override
								public void onFailure(Throwable caught) {
									// TODO Auto-generated method stub
									Window.alert("Problème de base de données. Veuillez recharger la page.");

								}

								@Override
								public void onSuccess(Integer result) {
									// TODO Auto-generated method stub
									
									dataService.delete("delete from teacher_document where teacher_login='"+teacherList.getValue(teacherList.getSelectedIndex())+"'", new AsyncCallback<Integer>() {

										@Override
										public void onFailure(Throwable caught) {
											// TODO Auto-generated method stub
											Window.alert("Problème de base de données. Veuillez recharger la page.");

										}

										@Override
										public void onSuccess(Integer result) {
											// TODO Auto-generated method stub
											
											dataService.delete("delete from teacher_subject where teacher_login='"+teacherList.getValue(teacherList.getSelectedIndex())+"'", new AsyncCallback<Integer>() {

												@Override
												public void onFailure(Throwable caught) {
													// TODO Auto-generated method stub
													Window.alert("Problème de base de données. Veuillez recharger la page.");

												}

												@Override
												public void onSuccess(Integer result) {
													// TODO Auto-generated method stub
													
													dataService.delete("delete from teacher where teacher_login='"+teacherList.getValue(teacherList.getSelectedIndex())+"'", new AsyncCallback<Integer>() {

														@Override
														public void onFailure(Throwable caught) {
															// TODO Auto-generated method stub
															Window.alert("Problème de base de données. Veuillez recharger la page.");

														}

														@Override
														public void onSuccess(Integer result) {
															// TODO Auto-generated method stub
															
														}
													});
												}
											});
										}
									});
								}
							});
						}
					});
					
				}
			}
		});
		
		addRemovePanel=new HorizontalPanel();
		addRemovePanel.add(addTeacherButton);
		addRemovePanel.add(removeTeacherButton);
		
		teacherPanel.add(teacherList);
		teacherPanel.add(addRemovePanel);
		
		
		listTeachedSubject = new ArrayList<String>();
		modifPanel = new VerticalPanel();
		modifPanel.setHorizontalAlignment(ALIGN_CENTER);
		quotaPanel = new VerticalPanel();
		quotaPanel.setHorizontalAlignment(ALIGN_CENTER);
		subjectPanel = new HorizontalPanel();
		buttonSubjectPanel = new VerticalPanel();
		subjectList1=new ListBox();
		subjectList1.setVisibleItemCount(10);
		subjectList2=new ListBox();
		subjectList2.setVisibleItemCount(10);
		addSubjectButton=new PushButton(new Image("right.png"));
		addSubjectButton.setSize("40px", "40px");
		addSubjectButton.addClickHandler(new ClickHandler()
		{

			@Override
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				subjectList2.addItem(subjectList1.getItemText(subjectList1.getSelectedIndex()),subjectList1.getValue(subjectList1.getSelectedIndex()));
				subjectList1.removeItem(subjectList1.getSelectedIndex());
			}
		
		});
		removeSubjectButton=new PushButton(new Image("left.png"));
		removeSubjectButton.setSize("40px", "40px");
		removeSubjectButton.addClickHandler(new ClickHandler()
		{

			@Override
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				subjectList1.addItem(subjectList2.getItemText(subjectList2.getSelectedIndex()),subjectList2.getValue(subjectList2.getSelectedIndex()));
				subjectList2.removeItem(subjectList2.getSelectedIndex());
			}
		
		});
		
		
		
		
		
		
		
		
		
		
		
		quotaTextBox = new ValidIntegerTextBox();
		
		
		
		rightsBox.addItem("Administrateur","0");
		rightsBox.addItem("Chef de filière","-1");
		rightsBox.addItem("Professeur","-1");
		rightsBox.addChangeHandler(new ChangeHandler() {
			
			@Override
			public void onChange(ChangeEvent event) {
				// TODO Auto-generated method stub
				if(((ListBox)event.getSource()).getSelectedIndex()!=1)
				{
					coursesBox.setEnabled(false);
				}
				else
				{
					coursesBox.setEnabled(true);
				}
					
			}
		});
		
		dataService.select("select course_id, course_name from course", new AsyncCallback<HashMap<String,String[]>>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				Window.alert("Problème de base de données. Veuillez recharger la page.");
			}

			@Override
			public void onSuccess(HashMap<String, String[]> result) {
				// TODO Auto-generated method stub
				for(int i=0;i<result.get("course_id").length;i++)
				{
					coursesBox.addItem(result.get("course_name")[i],result.get("course_id")[i]);
				}
			}
		});
		
		validSubjectButton = new PushButton("valider");
		validSubjectButton.setEnabled(false);
		validSubjectButton.addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				// TODO Auto-generated method stub
				for(int i=0;i<subjectList1.getItemCount();i++)
				{
					if(listTeachedSubject.contains(subjectList1.getItemText(i)))
					{
						String query="delete from teacher_subject where teacher_login='"+teacherList.getValue(teacherList.getSelectedIndex())+"' and subject_id="+subjectList1.getValue(i);
						
						dataService.delete(query, new AsyncCallback<Integer>() {

							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub
								Window.alert("Problème de base de données. Veuillez recharger la page.");
							}

							@Override
							public void onSuccess(Integer result) {
								// TODO Auto-generated method stub
								
							}
						});
					}
				}
				for(int i=0;i<subjectList2.getItemCount();i++)
				{
					if(!listTeachedSubject.contains(subjectList2.getItemText(i)))
					{
						
						String query="insert into teacher_subject (teacher_login,subject_id,teacher_subject_cm,teacher_subject_td,teacher_subject_tp) values ('"+teacherList.getValue(teacherList.getSelectedIndex())+"',"+subjectList2.getValue(i)+",0,0,0)";
						//Window.alert("add : "+teacherList.getValue(teacherList.getSelectedIndex())+" ___ "+subjectList2.getItemText(i));
						dataService.insert(query, new AsyncCallback<Integer>() {

							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub
								Window.alert("Problème de base de données. Veuillez recharger la page.");
							}

							@Override
							public void onSuccess(Integer result) {
								// TODO Auto-generated method stub
								
							}
						});
					}
				}
				int tempStatus=-1;
				if(rightsBox.getSelectedIndex()==0)
				{
					tempStatus=0;
				}
				else
					if(rightsBox.getSelectedIndex()==1)
					{
						tempStatus=new Integer(coursesBox.getValue(coursesBox.getSelectedIndex()));
					}
				String query="update teacher set teacher_quota="+new Double(quotaTextBox.getText())+" , teacher_status="+tempStatus+" where teacher_login='"+teacherList.getValue(teacherList.getSelectedIndex())+"'";
				dataService.update(query, new AsyncCallback<Integer>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						Window.alert("Problème de base de données. Veuillez recharger la page.");
					}

					@Override
					public void onSuccess(Integer result) {
						// TODO Auto-generated method stub
						
					}
				});
				Timer t=new Timer(){

					@Override
					public void run() {
						// TODO Auto-generated method stub
						showCoursePanel(teacherList.getValue(teacherList.getSelectedIndex()));
					}};
				t.schedule(500);
			}
		});
		
		
		modifGrid.setWidget(0,0,new Label("Quota horaire"));
		modifGrid.setWidget(0,1,quotaTextBox);
		modifGrid.setWidget(1,0,new Label("Statut"));
		modifGrid.setWidget(1,1,rightsBox);
		modifGrid.setWidget(2,0,new Label("Filière"));
		modifGrid.setWidget(2,1,coursesBox);

		
		buttonSubjectPanel.add(addSubjectButton);
		buttonSubjectPanel.add(removeSubjectButton);
		quotaPanel.add(modifGrid);
		quotaPanel.add(validSubjectButton);

		subjectPanel.add(subjectList1);
		subjectPanel.add(buttonSubjectPanel);
		subjectPanel.add(subjectList2);
		
		modifPanel.add(subjectPanel);
		modifPanel.add(quotaPanel);
		
		init();
		
		add(teacherPanel);
		add(modifPanel);
		onResize();
	}
	/**
	 * methode d'initialisation des données du panel
	 */
	public void init()
	{
		String query="select teacher_name,teacher_firstname,teacher_login from teacher order by teacher_name asc";
		dataService.select(query, new AsyncCallback<HashMap<String,String[]>>() {
			
			@Override
			public void onSuccess(HashMap<String, String[]> result) {
				// TODO Auto-generated method stub
				for(int i=0;i<result.get("teacher_login").length;i++)
				{
					teacherList.addItem(result.get("teacher_firstname")[i].charAt(0)+". "+result.get("teacher_name")[i],result.get("teacher_login")[i]);
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		});
		teacherList.addChangeHandler(new ChangeHandler() {
			@Override
			public void onChange(ChangeEvent event) {
				// TODO Auto-generated method stub
				validSubjectButton.setEnabled(true);
				showCoursePanel(((ListBox)event.getSource()).getValue(((ListBox)event.getSource()).getSelectedIndex()));
			}
		});
	}
	/**
	 * methode d'affichage des panels dynamiques en fonction du professeur selectionné
	 * @param l'identifiant de l'utilisateur selectionné
	 */
	public void showCoursePanel(String login)
	{
		listTeachedSubject.clear();
		final String log=login;
		subjectList1.clear();
		subjectList2.clear();
		String query1="select * from subject where subject_id not in (select subject_id from subject where subject_id in (select subject_id from teacher_subject where teacher_login='"+log+"'))";
		dataService.select(query1, new AsyncCallback<HashMap<String,String[]>>() {

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onSuccess(HashMap<String, String[]> result) {
				// TODO Auto-generated method stub
				for(int i=0;i<result.get("subject_id").length;i++)
				{
					subjectList1.addItem(result.get("subject_name")[i], result.get("subject_id")[i]);
				}
				
				String query2="select * from subject where subject_id in (select subject_id from teacher_subject where teacher_login='"+log+"')";
				dataService.select(query2, new AsyncCallback<HashMap<String,String[]>>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
					}

					@Override
					public void onSuccess(HashMap<String, String[]> result) {
						// TODO Auto-generated method stub

						for(int i=0;i<result.get("subject_id").length;i++)
						{
							subjectList2.addItem(result.get("subject_name")[i], result.get("subject_id")[i]);
							listTeachedSubject.add(result.get("subject_name")[i]);
						}

						String query3="select teacher_quota,teacher_status from teacher where teacher_login='"+log+"'";

						dataService.select(query3, new AsyncCallback<HashMap<String,String[]>>() {

							@Override
							public void onFailure(Throwable caught) {
								// TODO Auto-generated method stub
								Window.alert("erreur accès base de donnée.");
							}

							@Override
							public void onSuccess(HashMap<String, String[]> result) {
								// TODO Auto-generated method stub
								
								quotaTextBox.setText(result.get("teacher_quota")[0]);
								if(result.get("teacher_status")[0].equals("-1"))
								{
									rightsBox.setSelectedIndex(2);
									coursesBox.setEnabled(false);
								}
								else
									if(result.get("teacher_status")[0].equals("0"))
									{
										rightsBox.setSelectedIndex(0);
										coursesBox.setEnabled(false);
									}
									else
									{
										rightsBox.setSelectedIndex(1);
										coursesBox.setEnabled(true);
										for(int i=0;i<coursesBox.getItemCount();i++)
										{
											if(coursesBox.getValue(i).equals(result.get("teacher_status")[0]))
											{
												coursesBox.setSelectedIndex(i);
											}
										}
									}
							}
						});
					}
				});
			}
		});
	}
	/**
	 * methode de redimensionnement des éléments principaux du module
	 */
	public void onResize()
	{
		teacherList.setSize(Window.getClientWidth()*16/20*1/4+"px", Window.getClientHeight()*9/10*2/3+"px");
		subjectList1.setSize(Window.getClientWidth()*16/20*1/3+"px", Window.getClientHeight()*9/10*2/3+"px");
		subjectList2.setSize(Window.getClientWidth()*16/20*1/3+"px", Window.getClientHeight()*9/10*2/3+"px");
	}

}
